#include <iostream>
#include <pthread.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "RingQueue.hpp"
using namespace std;

void* producer(void* args)
{
    RingQueue<int>* rq = static_cast<RingQueue<int>*>(args);
    srand(time(nullptr));
    while(true)
    {
        int num = rand()%1000;
        rq->push(num);
        cout<<"生产:"<<num<<endl;
        usleep(8000);
    }
}

void* consumer(void* args)
{
    RingQueue<int>* rq = static_cast<RingQueue<int>*>(args);
    while(true)
    {
        int num = 0;
        rq->pop(&num);
        cout<<"消费:"<<num<<endl;
    }
}

void single() //单生产单消费
{
    RingQueue<int> rq(10);
    pthread_t _p,_c;
    
    pthread_create(&_p,nullptr,producer,(void*)(&rq)); //生产者线程
    pthread_create(&_c,nullptr,consumer,(void*)(&rq)); //消费者线程

    pthread_join(_p,nullptr);
    pthread_join(_c,nullptr);
}

void many() //多生产多消费
{
    RingQueue<int> rq;
    pthread_t _p[3],_c[2];

    for(int i = 0;i<3;++i) pthread_create(_p+i,nullptr,producer,(void*)(&rq)); //生产者线程
    for(int i = 0;i<2;++i) pthread_create(_c+i,nullptr,consumer,(void*)(&rq)); //消费者线程

    for(int i = 0;i<3;++i) pthread_join(*(_p+i),nullptr);
    for(int i = 0;i<2;++i) pthread_join(*(_c+i),nullptr);
}

int main()
{
    //single();
    many();
    return 0;
}